import { system } from "@minecraft/server";

export class Timer {
  run_id: number | undefined = undefined;
  delay: number | undefined = undefined;
  callback: () => void;

  constructor(callback: () => void, ticks?: number) {
    this.delay = ticks;
    this.callback = callback;
  }

  public start() {
    this.stop();
    this.run_id = system.runTimeout(this.callback, this.delay);
    return this;
  }

  public start_interval() {
    this.stop();
    this.run_id = system.runInterval(this.callback, this.delay);
    return this;
  }

  public start_interval_for(duration: number) {
    this.start_interval().start_sub_timeout_timer(() => {
      this.stop();
    }, duration);
  }

  public stop() {
    if (this.run_id != undefined) {
      system.clearRun(this.run_id);
      this.run_id = undefined;
    }
    return this;
  }

  public stop_ahead() {
    this.stop();
    this.callback();
  }

  //内部的计时器，可以用来停止间歇性计时器
  public start_sub_timeout_timer(callback: () => void, delay: number) {
    let subtimer = new Timer(callback, delay);
    subtimer.start();
    return this;
  }
}
